#pragma once

#include <iostream>
#include <string>
#include <unordered_set>
#include <fstream>

const int line_size = 1024;
class Command
{
private:
    std::unordered_set<std::string> _white_list;
public:
// zdl:: 给一个命令，并返回结果
    std::string execute(std::string cmdStr)
    {
        if (!_white_list.count(cmdStr)) return cmdStr + " do not suport!";
        // 1. pipe
        // 2. dup2(pipe[1], 1) + exec* + fork, 执行结果给父进程
        // 3. return 
        FILE* fp = ::popen(cmdStr.c_str(), "r");
        std::string retsult;
        if (nullptr == fp)
        {
            return std::string("execite failed");
        }
        char buffer[line_size];
        while (true)
        {
            char* ret = ::fgets(buffer, sizeof(buffer), fp);
            if (ret == nullptr) break;
            retsult += ret;
        }
        
        pclose(fp);
        return retsult.empty() ? "done" : std::string(retsult);
    }
    Command()
    {
        std::fstream in("./cmd.txt");
        std::string cmd;
        while(std::getline(in, cmd))
        {
            _white_list.insert(cmd);
        }
    }
    bool safeCheck(const std::string &cmdStr)
    {
        auto iter = _white_list.find(cmdStr);
        return iter == _white_list.end()? false : true;
    }
};